import { message } from "./scripts/util.js";
import { getCompareElements } from "./scripts/contain.js";

document.addEventListener("DOMContentLoaded", function () {
  const confirmButton = document.getElementById(
    "confirm-button"
  ) as HTMLButtonElement;
  const minInput = document.getElementById("min-input") as HTMLInputElement;
  const maxInput = document.getElementById("max-input") as HTMLInputElement;

  // 1. 加载时读取存储值（回显）
  chrome.storage.local.get(["min", "max"], (result) => {
    minInput.value = result.min || 6;
    maxInput.value = result.max || 6.6;
  });

  // 2. 确认按钮添加点击事件
  confirmButton.addEventListener("click", function () {
    if (!minInput.value || !maxInput.value) message.error("请输入最小值和最大值");
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      const activeTab = tabs[0];
      chrome.scripting.executeScript({
        target: { tabId: activeTab.id as number },
        // @ts-ignore
        func: (min: number, max: number) => {
          // 1 获取所有元素，并移除无关项
          const discountElms = [...document.querySelectorAll("div.Form_itemHelper_5-141-0 .Grid_col_5-141-0")] as HTMLDivElement[]
          discountElms.pop()
          // 2 对比数字，显示颜色
          discountElms.forEach((ele) => {
            const disCount = ele.innerText.match(/[\d\.]+/)?.[0] || 0
            // 3 如果小于最小值
            if (+disCount < min) ele.style.color = 'red'
            // 4 如果大于最大值
            if (+disCount > max) ele.style.color = '#09f'
          })
        },
        args: [+minInput.value, +maxInput.value],
      });
    });
  });
});

